package com.zzl.mq.network.gossip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import java.util.*;

@Component
@EnableConfigurationProperties
public class NodeBootstrap {
    private static final Logger log = LoggerFactory.getLogger(NodeBootstrap.class);
    
    private final ClusterNodeManager nodeManager;
    private final GossipManager gossipManager;
    
    
    @Value("${mq.network.node-id}")
    private String nodeId;
    
    private final ClusterConfig clusterConfig;
    
    public NodeBootstrap(ClusterNodeManager nodeManager, GossipManager gossipManager, ClusterConfig clusterConfig) {
        this.nodeManager = nodeManager;
        this.gossipManager = gossipManager;
        this.clusterConfig = clusterConfig;
    }
    
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        ClusterNode locaClusterNode = null;
        // 添加配置中的其他节点
        for (NodeConfig nodeConfig : clusterConfig.getNodes()) {
            // 跳过当前节点
            if (nodeConfig.getNodeId().equals(nodeId)) {
                ClusterNode node = new ClusterNode(
                    nodeConfig.getNodeId(),
                    nodeConfig.getHost(),
                    nodeConfig.getPort()
                );
                nodeManager.addNode(node);
                locaClusterNode = node;
                continue;
            }
            
            ClusterNode node = new ClusterNode(
                nodeConfig.getNodeId(),
                nodeConfig.getHost(),
                nodeConfig.getPort()
            );
            nodeManager.addNode(node);
            log.info("Added cluster node: {}", node.getNodeId());
        }
        
        if (locaClusterNode == null) {
            log.error("Local node configuration not found in cluster config. Shutting down application.");
            System.exit(1);
        }
        
        // 创建加入消息
        GossipMessage joinMessage = new GossipMessage();
        joinMessage.setMessageId(UUID.randomUUID().toString());
        joinMessage.setNodeId(nodeId);
        joinMessage.setType(GossipMessage.MessageType.NODE_JOIN);
        joinMessage.setPayload(locaClusterNode);
        joinMessage.setTimestamp(System.currentTimeMillis());
        
        // 传播加入消息
        gossipManager.spreadMessage(joinMessage);
        log.info("Node {} started and joined the cluster at {}:{}", nodeId, locaClusterNode.getHost(), locaClusterNode.getPort());
    }
} 